package BFS;

import java.util.*;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2024-03-10
 * Time:16:26
 * Text：1926. 迷宫中离入口最近的出口
 */
public class Texts1 {
    int[] dx={0,0,1,-1};
    int[] dy={1,-1,0,0};
    boolean[][] arr;
    public int nearestExit(char[][] maze, int[] e) {
        Queue<int[]> q=new LinkedList<>();
        int ret=0;
        int x=maze.length,y=maze[0].length;
        arr=new boolean[x][y];
        arr[e[0]][e[1]]=true;
        q.add(new int[]{e[0],e[1]});
        while(!q.isEmpty())
        {
            ret++;
            int size=q.size();
            while(size-->0)
            {
                int[] array=q.poll();
                for(int i=0;i<4;i++)
                {
                    int x1=dx[i]+array[0],y1=dy[i]+array[1];

                    if(x1>=0 && y1>=0 && x1 < x && y1 < y && maze[x1][y1]=='.' && !arr[x1][y1])
                    {
                        if(x1==0 || y1==0 || x1==x-1 || y1==y-1)
                        {
                            return ret;
                        }
                        arr[x1][y1]=true;
                        q.add(new int[]{x1,y1});
                    }
                }
            }
        }
        return -1;
    }
}